<template>
    <div class="house-list">
        <Header />
        
        <PageBanner
            title="热门房产"
            :breadcrumbs="[
                { title: '房产', path: '/house' },
                { title: '热门房产' }
            ]"
        />
        
        <!-- 主要内容区域 -->
        <div class="container">
            <div class="content-wrapper">
                <!-- 视图切换器 -->
                <ViewSwitcher
                    @viewChange="handleViewChange"
                    @categoryChange="handleCategoryChange"
                    @showFilter="showFilterModal"
                />
                
                <!-- 房产列表 -->
                <div :class="currentView === 'grid' ? 'house-grid' : 'house-list'">
                    <template v-if="currentView === 'grid'">
                        <HouseCard 
                            v-for="house in houses.list" 
                            :key="house.houseId" 
                            :house="house"
                            @click="handleHouseClick(house)"
                        />
                    </template>
                    <template v-else>
                        <HouseListItem
                            v-for="(house, index) in houses.list"
                            :key="house.houseId"
                            :house="house"
                            :is-reverse="index % 2 !== 0"
                            @click="handleHouseClick(house)"
                        />
                    </template>
                </div>
                
                <!-- 加载中状态 -->
                <div v-if="loading" class="loading">
                    <el-loading />
                </div>
                
                <!-- 无数据展示 -->
                <div v-if="!loading && (!houses.list || houses.list.length === 0)" class="no-data">
                    <svg-icon name="common/no-data" />
                    <p>暂无相关房产</p>
                </div>
                
                <Pagination
                    v-if="houses.list && houses.list.length > 0"
                    v-model:currentPage="queryParams.current"
                    :total="houses.total"
                    :page-size="queryParams.size"
                    :page-sizes="[3, 9]"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"
                />
            </div>
        </div>
        
        <Footer />
        
        <!-- 筛选弹窗 -->
        <el-dialog
            v-model="filterDialogVisible"
            title="房产筛选"
            width="80%"
            destroy-on-close
        >
            <el-form :model="queryParams.filters" label-width="100px">
                <el-form-item label="价格区间">
                    <el-slider
                        v-model="queryParams.filters.priceRange"
                        range
                        :min="0"
                        :max="2000"
                        :step="10"
                    />
                </el-form-item>
                <el-form-item label="面积区间">
                    <el-slider
                        v-model="queryParams.filters.areaRange"
                        range
                        :min="0"
                        :max="500"
                        :step="10"
                    />
                </el-form-item>
                <el-form-item label="房屋类型">
                    <el-select v-model="queryParams.filters.houseType">
                        <el-option label="整租" value="1" />
                        <el-option label="合租" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="卧室数量">
                    <el-input-number v-model="queryParams.filters.bedroom" :min="1" :max="10" />
                </el-form-item>
                <el-form-item label="所在区域">
                    <el-select v-model="queryParams.filters.district">
                        <el-option label="朝阳区" value="朝阳区" />
                        <el-option label="海淀区" value="海淀区" />
                        <el-option label="东城区" value="东城区" />
                        <el-option label="西城区" value="西城区" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="filterDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleFilterConfirm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getHotHouses } from '@/api/house'
import Header from '@/views/common/Header.vue'
import Footer from '@/views/common/Footer.vue'
import PageBanner from '@/views/common/PageBanner.vue'
import HouseCard from './components/HouseCard.vue'
import HouseListItem from './components/HouseListItem.vue'
import ViewSwitcher from './components/ViewSwitcher.vue'
import Pagination from '@/views/common/Pagination.vue'
import { ElMessage, ElDialog, ElForm, ElFormItem, ElButton, ElSelect, ElOption, ElSlider, ElInputNumber, ElLoading } from 'element-plus'
import 'element-plus/dist/index.css'
import { enrichHousesWithAgentInfo } from '@/utils/agentHelper'

const router = useRouter()
const loading = ref(false)
const filterDialogVisible = ref(false)

// 查询参数
const queryParams = reactive({
    current: 1,
    size: 9,  // 默认网格视图9条
    filters: {
        priceRange: [0, 1000],
        areaRange: [0, 200],
        houseType: '1',
        propertyType: '1',
        bedroom: 2,
        district: '',
        subway: null,
        station: null,
        distance: null,
        orientation: '',
        decoration: '',
        tags: [],
        facilities: []
    },
    sort: {
        field: 'createTime',
        order: 'desc'
    }
})

// 房产数据
const houses = reactive({
    total: 0,
    pages: 0,
    current: 1,
    size: 9,  // 默认网格视图9条
    list: []
})

const currentView = ref('grid')

// 获取房产列表数据
const fetchHouses = async () => {
    loading.value = true
    try {
        // 简化基础参数
        const params = new URLSearchParams()
        params.append('pageNum', queryParams.current)
        params.append('pageSize', queryParams.size)
        
        // 添加筛选条件
        if (queryParams.filters.priceRange?.length === 2) {
            params.append('minPrice', queryParams.filters.priceRange[0])
            params.append('maxPrice', queryParams.filters.priceRange[1])
        }
        if (queryParams.filters.areaRange?.length === 2) {
            params.append('minArea', queryParams.filters.areaRange[0])
            params.append('maxArea', queryParams.filters.areaRange[1])
        }
        if (queryParams.filters.houseType) {
            params.append('houseType', queryParams.filters.houseType)
        }
        if (queryParams.filters.bedroom) {
            params.append('bedroom', queryParams.filters.bedroom)
        }
        if (queryParams.filters.district) {
            params.append('district', queryParams.filters.district)
        }
        
        // 添加排序参数
        if (queryParams.sort.field) {
            params.append('sortField', queryParams.sort.field)
            params.append('sortOrder', queryParams.sort.order)
        }

        const response = await getHotHouses(params)
        
        if (response.code === 200) {
            const { records } = response.data
            
            // 转换基本字段
            let mappedHouses = records.map(house => ({
                id: house.houseId,
                houseId: house.houseId, // 确保两种ID格式都有
                title: house.title,
                coverImage: house.coverImage,
                price: house.price,
                address: `${house.district}${house.street ? ` ${house.street}` : ''}`,
                bedroom: house.bedroom,
                bathroom: house.bathroom,
                area: house.area,
                agentId: house.agentId, // 确保保留agentId
                agentName: house.agentName,
                agentAvatar: house.agentAvatar,
                remark: house.remark,
                tags: house.tags || []
            }))
            
            // 使用工具函数补充经纪人信息
            mappedHouses = await enrichHousesWithAgentInfo(mappedHouses)
            
            // 手动计算总数和页数
            houses.total = records.length
            houses.current = queryParams.current
            houses.size = queryParams.size
            houses.pages = Math.ceil(records.length / queryParams.size)
            
            // 根据当前页和每页数量截取数据
            const start = (houses.current - 1) * houses.size
            const end = start + houses.size
            houses.list = mappedHouses.slice(start, end)
            
            console.log('热门房源数据（含经纪人信息）:', houses.list)
            console.log('分页信息：', {
                current: houses.current,
                size: houses.size,
                total: houses.total,
                pages: houses.pages
            })
        } else {
            ElMessage.error(response.msg || '获取数据失败')
        }
    } catch (error) {
        console.error('获取热门房源失败:', error)
        ElMessage.error('获取数据失败，请稍后重试')
    } finally {
        loading.value = false
    }
}

// 滚动到页面横幅位置
const scrollToBanner = () => {
    const pageBanner = document.querySelector('.page-banner')
    if (pageBanner) {
        const rect = pageBanner.getBoundingClientRect()
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop
        const targetPosition = scrollTop + rect.top

        requestAnimationFrame(() => {
            window.scrollTo({
                top: targetPosition,
                behavior: 'smooth'
            })
        })
    }
}

// 处理每页显示数量变化
const handleSizeChange = async (size) => {
    loading.value = true
    queryParams.size = size
    queryParams.current = 1
    await fetchHouses()
    scrollToBanner()
}

// 处理视图切换
const handleViewChange = async (view) => {
    loading.value = true
    currentView.value = view
    // 切换视图时更新每页显示数量
    queryParams.size = view === 'grid' ? 9 : 3  // 网格视图9条，列表视图3条
    queryParams.current = 1
    await fetchHouses()
    scrollToBanner()
}

// 处理分类切换
const handleCategoryChange = (category) => {
    switch (category) {
        case 'hot':
            router.push('/house/hot')
            break
        case 'new':
            router.push('/house/new')
            break
        default:
            router.push('/house')
    }
}

// 处理页码变化
const handlePageChange = async (page) => {
    loading.value = true
    queryParams.current = page
    await fetchHouses()
    scrollToBanner()
}

// 处理筛选条件
const showFilterModal = () => {
    filterDialogVisible.value = true
}

// 处理筛选确认
const handleFilterConfirm = () => {
    filterDialogVisible.value = false
    queryParams.current = 1
    fetchHouses()
}

// 处理房产点击
const handleHouseClick = (house) => {
    router.push({
        name: 'HouseDetail',
        params: { id: house.id }
    })
}

// 初始化加载数据
onMounted(() => {
    fetchHouses()
})
</script>

<style lang="scss" scoped>
.house-list {
    width: 100%;
    display: flex;
    flex-direction: column;
    
    .container {
        width: 100%;
        padding: 0 60px;
        box-sizing: border-box;
        margin: 60px auto;
        
        .content-wrapper {
            max-width: 1320px;
            margin: 0 auto;
            
            .house-grid {
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 24px;
                margin: 30px 0;
            }
            
            .house-list {
                display: flex;
                flex-direction: column;
                margin: 30px 0;
            }
            
            .loading {
                text-align: center;
                padding: 60px 0;
            }
            
            .no-data {
                text-align: center;
                padding: 60px 0;
                color: #6d737a;
                
                .svg-icon {
                    width: 120px;
                    height: 120px;
                    margin-bottom: 16px;
                }
                
                p {
                    font-size: 16px;
                }
            }
        }
    }
}
</style> 